package com.controller;

import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.base.BaseControllers;

@Controller
@RequestMapping("/user")
public class FileUploadController extends BaseControllers{
	
	 @RequestMapping(value="/fileupload")
	 public ModelAndView index() {
	     Map<String,Object>  context = new HashMap<String, Object>();
	     return forword("user/fileupload",context);
	}
	@RequestMapping(value = "/fileuploadForm")
	@ResponseBody
	public Map fileuploadForm(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		//Map<String,Object>  context = getRootMap();
		// 创建一个通用的多部分解析器.
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 设置编码
		commonsMultipartResolver.setDefaultEncoding("utf-8");
		// 判断 request 是否有文件上传,即多部分请求...
		if (commonsMultipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
			// file 是指 文件上传标签的 name=值
			// 根据 name 获取上传的文件...
			MultipartFile file = multipartRequest.getFile("txtfile");
			// 上传后记录的文件...
			String filePathString=request.getSession().getServletContext().getRealPath("/") +"xxx.txt";
			File imageFile = new File(filePathString);
			// 上传...
			file.transferTo(imageFile);
			return Collections.singletonMap(SUCCESS,true);
		}
		return Collections.singletonMap(SUCCESS,false);
	}
}
